﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using SBACN.WebSite.Models;

namespace SBACN.WebSite.Cache
{
	public class SystemConfigCache
	{
		public static readonly SystemConfigCache Instance = new SystemConfigCache();
		private SystemConfigCache()
		{ }
		private object SyncRoot = new object();
		private IDictionary<int, TB_SystemConfig> _CacheDictionary = null;
		private IDictionary<int, TB_SystemConfig> CacheDictionary
		{
			get
			{
				if (_CacheDictionary == null || _CacheDictionary.Count == 0)
				{
					ReLoadFromDB();
				}
				return _CacheDictionary;
			}
		}
		public IList<TB_SystemConfig> List
		{
			get
			{
				IList<TB_SystemConfig> list = new List<TB_SystemConfig>();
				lock (SyncRoot)
				{
					if (CacheDictionary != null)
					{
						list = CacheDictionary.Values.ToList<TB_SystemConfig>();
					}
				}
				return list;
			}
		}

		private void ReLoadFromDB()
		{
			Expression<Func<TB_SystemConfig, bool>> f = (p => true);
			Expression<Func<TB_SystemConfig, string>> o = (p => p.Type);
			var systemConfigList = DAL.DALHelper.Instance.GetList<TB_SystemConfig, string>(f, o, true);
			lock (SyncRoot)
			{
				_CacheDictionary = new Dictionary<int, TB_SystemConfig>();
				foreach (var item in systemConfigList)
				{
					if (_CacheDictionary.ContainsKey(item.ID))
					{
						_CacheDictionary[item.ID] = item;
					}
					else
					{
						_CacheDictionary.Add(item.ID, item);
					}
				}
			}
		}

		public IList<TB_SystemConfig> this[string type]
		{
			get
			{
				IList<TB_SystemConfig> list = new List<TB_SystemConfig>();
				lock (SyncRoot)
				{
					list = List.Where(p => p.Type == type).ToList();
				}
				return list;
			}
		}

		public void Add(TB_SystemConfig systemConfig)
		{
			lock (SyncRoot)
			{
				if (CacheDictionary.ContainsKey(systemConfig.ID))
				{
					CacheDictionary[systemConfig.ID] = systemConfig;
				}
				else
				{
					CacheDictionary.Add(systemConfig.ID, systemConfig);
				}
			}
		}

		public void Remove(TB_SystemConfig systemConfig)
		{
			Remove(systemConfig.ID);
		}

		public void Remove(int id)
		{
			lock (SyncRoot)
			{
				CacheDictionary.Remove(id);
			}
		}

		public void Clear()
		{
			lock (SyncRoot)
			{
				CacheDictionary.Clear();
			}
		}
	}
}